<?php
class TvbFmsDistributor extends BaseDistributor {
	const FMS_BASE = 'rtmpe://streaming.tvb.com/vi';
	const SMIL_PREFIX = '/data/video_infrastructure/smil';
	
	public function getDestinationId() {
		return 1;
	}

	public function distribute(array $data) {
		return TRUE;
	}
	
	public function getVideo($export_id) {
		$rf = VideoInfrastructure::GetReadableRecordFactory();
		
		$found = $rf->find(
			'Distribution',
			'export_id=? AND destination_id=?',
			array($export_id, $this->getDestinationId())
		);
		
		if (!$found) {
			return -2;	// Export video not found
		}
		
		$distribution_entry = array_shift($found);
		
		if ($distribution_entry->status != 1) {
			return $distribution_entry->status; // Video is not ready
		}
		
		$export_entry = $rf->findInstance('Export', $export_id);
		if (!$export_entry) {
			return -3;
		}
		
		$other_info = json_decode($distribution_entry->other_info, TRUE);
		$file = $other_info['fms_video_source'];
		$file = str_replace('//', '/', $other_info['fms_video_source']);
		$smil = "http://fms.api.tvb.com/getSmil.php?source_id={$export_entry->source_id}";
		
		return array(
			'app_url' => self::FMS_BASE,
			'file' => "mp4:{$file}",
			'smil' => $smil,
		);
	}
	
	public function getVideoListBySourceId($source_id) {
	}
	
	public function generateSmilFile($export_id) {
		$destination_id = $this->getDestinationId();
		$rf = VideoInfrastructure::getWritableRecordFactory();
		$export_entry = $rf->findInstance('Export', $export_id);
		if (!$export_entry) {
			return FALSE;
		}
		
		$source_entry = $rf->findInstance('Source', $export_entry->source_id);
		if (!$source_entry) {
			return FALSE;
		}
		
		$export_entry_list = $rf->findBySql('Export', "SELECT * FROM export WHERE source_id={$source_entry->id} AND ready=" . VideoInfrastructure::STATUS_ACTIVE . " ORDER BY video_bitrate DESC, audio_bitrate DESC, id");
		if (!$export_entry_list) {
			return FALSE;
		}
		
		$distribution_entry_list = array();
		foreach ($export_entry_list as $export_entry_temp) {
			$found = $rf->find('Distribution', 'export_id=? AND destination_id=? AND status=?', array($export_entry_temp->id, $destination_id, VideoInfrastructure::STATUS_ACTIVE));
			
			if (!$found) {
				continue;
			}
			
			$distribution_entry = array_shift($found);
			$distribution_entry->video_bitrate = $export_entry_temp->video_bitrate;
			$distribution_entry->audio_bitrate = $export_entry_temp->audio_bitrate;
			$distribution_entry_list[] = $distribution_entry;
		}

		$app_url = self::FMS_BASE;
		$smil = <<< SMIL
<smil>
	<head>
		<meta base="{$app_url}" />
		<layout> 
			<root-layout width="{$export_entry->width}" height="{$export_entry->height}" /> 
		</layout>
	</head>
	<body>
		<switch>

SMIL;
		foreach ($distribution_entry_list as $distribution_entry) {
			$other_info = json_decode($distribution_entry->other_info, TRUE);
			$file = str_replace('//', '/', $other_info['fms_video_source']);
			$bitrate = $distribution_entry->video_bitrate + $distribution_entry->audio_bitrate;
			
			$duration = $source_entry->duration;
			$hh = (int) floor($duration / 3600);
			$duration -= $hh * 3600;
			
			$mm = (int) floor($duration / 60);
			$ss = $duration - $mm * 60;
			
			$smil .= <<< SMIL
			<video src="mp4:{$file}" system-bitrate="{$bitrate}" dur="{$hh}:{$mm}:{$ss}"/>

SMIL;
		}
		
		$smil .= <<< SMIL
		</switch>
	</body>
</smil>
SMIL;

		$hash = ceil($source_entry->id / 100);
		$filename = sprintf("%012d.smil", $source_entry->id );
		$file = self::SMIL_PREFIX . "/{$hash}/{$filename}";
		$dir = dirname($file);
		$ret = @mkdir($dir, 0777, TRUE);
		$ret = @chmod($dir, 0777);
		$ret = file_put_contents($file, $smil);
		if (!$ret) {
			return FALSE;
		}
		$ret = @chmod($file, 0666);
		
		return $file;
	}
	
	public function pushSmilFile($export_id, $destination_hosts, $port, $user, $public_key_file, $private_key_file, $passpharse) {
		$smil_file = $this->generateSmilFile($export_id);
		$result = TRUE;
		try {
			foreach ($destination_hosts as $host) {
				$ssh = new SSHAgent($host, $port, $user, $public_key_file, $private_key_file, $passpharse);
				$ret = $ssh->sendFile($smil_file, $smil_file);
				if (!$ret) {
					$result = FALSE;
				}
			}
		} catch (Exception $e) {
		}
		
		return $result;
	}
}

$distributor = new TvbFmsDistributor();
$ret = DistributorFactory::getInstance()->register($distributor->getDestinationId(), $distributor);
?>
